﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;
using YAPACS.BusinessObjects.Exams;
using YAPACS.BusinessObjects.Managements.Exams;
using YAPACS.RisServer.Workflows.SyncData;

namespace YAPACS.RisServer.Controllers;
[Authorize]
[ApiController]
public class ApplyDepartmentController : AbpControllerBase
{
    private readonly IRepository<ApplyDepartment, Guid> _applyDepartmentRepository;
    private readonly IRepository<ApplyDoctor, Guid> _applyDoctorRepository;
    private readonly IGetApplyDepartment _getApplyDepartment;
    private readonly IRepository<Exam, Guid> _examRepository;

    public ApplyDepartmentController(IRepository<ApplyDepartment, Guid> applyDepartmentRepository,
                                    IRepository<ApplyDoctor, Guid> applyDoctorRepository,
                                    IGetApplyDepartment getApplyDepartment, IRepository<Exam, Guid> examRepository)
    {
        _applyDepartmentRepository = applyDepartmentRepository;
        _applyDoctorRepository = applyDoctorRepository;
        _getApplyDepartment = getApplyDepartment;
        _examRepository = examRepository;
    }

    [HttpGet]
    [Route("api/get-apply-department-options")]
    public async Task<IActionResult> GetApplyDepartmentOptions()
    {
        List<ApplyDepartment> list = (await _applyDepartmentRepository.GetListAsync(e => e.IsActive))
                                     .OrderBy(e => e.Order).ThenBy(e=>e.CreationTime).ToList();// 注意，没有任何过滤条件
        var result = list.Select(e => new
        {
            Label = e.Name,
            Value = e.Id
        });
        return Ok(result);
    }

    [HttpGet("api/get-apply-doctors")]
    public async Task<IActionResult> GetApplyDoctors([FromQuery] Guid? applyDepartment)
    {
        if (applyDepartment.HasValue)
        {
            List<ApplyDoctor> list = await _applyDoctorRepository.GetListAsync(e => e.Department.Oid == applyDepartment && e.IsActive);
            list = list.OrderBy(e => e.Order).ThenBy(e => e.CreationTime).ThenBy(e => e.Name).ToList();
            var result = list.Select(e => new
            {
                Label = e.Name,
                Value = e.Id
            });
            return Ok(result);
        }
        return Ok();
    }

    [AllowAnonymous]
    [HttpGet]
    [Route("api/get-apply-departments")]
    public async Task<IActionResult> GetApplyDepartments([FromQuery] string institutionCode)
    {
        try
        {
            var result = await _getApplyDepartment.InvokeAsync(new YAPACS.Workflows.WorkflowInput()
            {
                {"InstitutionCode", institutionCode}
            });
            return Ok(result);
        }
        catch (Exception ex)
        {
            return Ok(new { Success = false, Error = ex.Message });
        }
    }
}
